<script setup>
import { ref, onMounted, computed } from 'vue'
import ApiService from '@/services/ApiService'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { hasPermission } from '@/utils/auth'
import { 
  Plus,
  Loading,
  Check,
  Close,
  Menu,
  Setting,
  Service
} from '@element-plus/icons-vue'

const authStore = useAuthStore()
const roles = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const currentRole = ref(null)
const editMode = ref(false)

// 新角色表单
const roleForm = ref({
  id: '',
  name: '',
  description: '',
  permissions: []
})

// 所有可选权限
const availablePermissions = ref([
  { 
    resource: 'app', 
    icon: Menu,
    label: '应用管理',
    actions: [
      { id: 'view', label: '查看' },
      { id: 'create', label: '创建' },
      { id: 'edit', label: '编辑' },
      { id: 'delete', label: '删除' }
    ]
  },
  { 
    resource: 'task', 
    icon: Setting,
    label: '任务管理',
    actions: [
      { id: 'view', label: '查看' },
      { id: 'create', label: '创建' },
      { id: 'edit', label: '编辑' },
      { id: 'delete', label: '删除' },
      { id: 'execute', label: '执行' },
      { id: 'stop', label: '停止' }
    ]
  },
  { 
    resource: 'robot', 
    icon: Service,
    label: '机器人管理',
    actions: [
      { id: 'view', label: '查看' },
      { id: 'create', label: '创建' },
      { id: 'edit', label: '编辑' },
      { id: 'delete', label: '删除' },
      { id: 'connect', label: '连接' },
      { id: 'restart', label: '重启' }
    ]
  }
])

// 权限分组计数
const permissionCounts = computed(() => {
  const counts = {}
  availablePermissions.value.forEach(group => {
    const resource = group.resource
    const total = group.actions.length
    const selected = group.actions.filter(action => 
      roleForm.value.permissions.includes(`${resource}:${action.id}`)
    ).length
    counts[resource] = { total, selected }
  })
  return counts
})

// 检查权限 - 只有管理员可以管理角色
const canManageRoles = computed(() => hasPermission('*'))

// 加载所有角色
const loadRoles = async () => {
  loading.value = true
  try {
    roles.value = await ApiService.getRoles()
    loading.value = false
  } catch (error) {
    ElMessage.error('加载角色列表失败')
    loading.value = false
  }
}

// 打开新建角色对话框
const openCreateDialog = () => {
  editMode.value = false
  roleForm.value = {
    id: '',
    name: '',
    description: '',
    permissions: []
  }
  dialogVisible.value = true
}

// 打开编辑角色对话框
const openEditDialog = (role) => {
  editMode.value = true
  currentRole.value = role
  roleForm.value = {
    id: role.id,
    name: role.name,
    description: role.description,
    permissions: [...role.permissions]
  }
  dialogVisible.value = true
}

// 删除角色
const handleDeleteRole = (role) => {
  ElMessageBox.confirm(
    `确定要删除角色 "${role.name}" 吗？这将会移除所有使用此角色的用户权限。`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    loading.value = true
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 800))
      
      // 从列表中移除角色（实际应用中应该调用API）
      roles.value = roles.value.filter(r => r.id !== role.id)
      
      ElMessage.success(`角色 ${role.name} 已删除`)
      loading.value = false
    } catch (error) {
      ElMessage.error('删除角色失败')
      loading.value = false
    }
  }).catch(() => {
    // 取消删除
  })
}

// 保存角色
const saveRole = async () => {
  // 表单验证
  if (!roleForm.value.name) {
    ElMessage.warning('角色名称不能为空')
    return
  }
  
  if (roleForm.value.permissions.length === 0) {
    ElMessage.warning('请至少选择一个权限')
    return
  }
  
  loading.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (editMode.value) {
      // 编辑现有角色
      const index = roles.value.findIndex(r => r.id === roleForm.value.id)
      if (index !== -1) {
        roles.value[index] = { ...roleForm.value }
      }
      ElMessage.success(`角色 ${roleForm.value.name} 已更新`)
    } else {
      // 创建新角色
      const newRole = {
        ...roleForm.value,
        id: 'role-' + Date.now() // 生成临时ID
      }
      roles.value.push(newRole)
      ElMessage.success(`角色 ${newRole.name} 已创建`)
    }
    
    dialogVisible.value = false
    loading.value = false
  } catch (error) {
    ElMessage.error(editMode.value ? '更新角色失败' : '创建角色失败')
    loading.value = false
  }
}

// 检查是否选择了某个权限
const isPermissionSelected = (resource, actionId) => {
  const permissionStr = `${resource}:${actionId}`
  return roleForm.value.permissions.includes(permissionStr) || roleForm.value.permissions.includes('*')
}

// 切换单个权限
const togglePermission = (resource, actionId) => {
  const permissionStr = `${resource}:${actionId}`
  const index = roleForm.value.permissions.indexOf(permissionStr)
  
  // 如果已经有通配符权限，先移除它
  const wildcardIndex = roleForm.value.permissions.indexOf('*')
  if (wildcardIndex !== -1) {
    roleForm.value.permissions.splice(wildcardIndex, 1)
  }
  
  if (index === -1) {
    roleForm.value.permissions.push(permissionStr)
  } else {
    roleForm.value.permissions.splice(index, 1)
  }
}

// 切换资源组所有权限
const toggleResourcePermissions = (resource, checked) => {
  const resourcePermissions = availablePermissions.value
    .find(p => p.resource === resource)
    .actions.map(action => `${resource}:${action.id}`)
  
  if (checked) {
    // 添加所有权限
    resourcePermissions.forEach(permission => {
      if (!roleForm.value.permissions.includes(permission)) {
        roleForm.value.permissions.push(permission)
      }
    })
  } else {
    // 移除所有权限
    roleForm.value.permissions = roleForm.value.permissions.filter(
      p => !resourcePermissions.includes(p)
    )
  }
}

// 是否选择了某个资源的所有权限
const isResourceFullySelected = (resource) => {
  if (roleForm.value.permissions.includes('*')) return true
  
  const { total, selected } = permissionCounts.value[resource] || { total: 0, selected: 0 }
  return total > 0 && selected === total
}

// 是否选择了某个资源的部分权限
const isResourcePartiallySelected = (resource) => {
  if (roleForm.value.permissions.includes('*')) return false
  
  const { total, selected } = permissionCounts.value[resource] || { total: 0, selected: 0 }
  return selected > 0 && selected < total
}

// 设置全部权限
const setAllPermissions = () => {
  roleForm.value.permissions = ['*']
}

// 清除全部权限
const clearAllPermissions = () => {
  roleForm.value.permissions = []
}

// 初始化
onMounted(async () => {
  await loadRoles()
})
</script>

<template>
  <div class="role-management-container" v-if="canManageRoles">
    <el-card class="role-card">
      <template #header>
        <div class="page-header">
          <div class="page-title">
            <h2>角色管理</h2>
          </div>
          <el-button type="primary" @click="openCreateDialog">
            <el-icon style="margin-right: 5px;"><Plus /></el-icon>新建角色
          </el-button>
        </div>
      </template>
      
      <div class="card-body">
        <!-- Loading spinner -->
        <div v-if="loading" class="loading-container">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span class="loading-text">加载中...</span>
        </div>
        
        <!-- Role Table -->
        <div v-else class="table-container">
          <el-table :data="roles" style="width: 100%" table-layout="fixed" :max-height="450">
            <el-table-column prop="id" label="角色ID" width="100" :show-overflow-tooltip="true" />
            <el-table-column prop="name" label="角色名称" width="120">
              <template #default="scope">
                <div class="role-name-cell">
                  <el-tag 
                    :type="
                      scope.row.name === '管理员' ? 'danger' : 
                      scope.row.name === '经理' ? 'warning' : 
                      scope.row.name === '操作员' ? 'success' : 'info'
                    "
                  >{{ scope.row.name }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="120" :show-overflow-tooltip="true" />
            <el-table-column label="权限" min-width="280">
              <template #default="scope">
                <div class="permission-tags">
                  <el-tag 
                    v-if="scope.row.permissions.includes('*')" 
                    type="success"
                    effect="dark"
                  >所有权限</el-tag>
                  <template v-else>
                    <div class="permission-summary">
                      <el-tooltip
                        v-for="group in availablePermissions"
                        :key="group.resource"
                        effect="dark"
                        :content="scope.row.permissions
                          .filter(p => p.startsWith(group.resource + ':'))
                          .map(p => p.split(':')[1])
                          .join(', ')"
                        placement="top"
                      >
                        <el-tag 
                          type="info"
                          style="margin-right: 5px; margin-bottom: 5px;"
                          :type="scope.row.permissions.some(p => p.startsWith(group.resource)) ? 'primary' : 'info'"
                        >
                          <el-icon class="permission-icon"><component :is="group.icon" /></el-icon>
                          {{ group.label }}
                          <span class="permission-count">
                            {{ scope.row.permissions.filter(p => p.startsWith(group.resource)).length }}/{{ group.actions.length }}
                          </span>
                        </el-tag>
                      </el-tooltip>
                    </div>
                  </template>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="openEditDialog(scope.row)"
                    :disabled="scope.row.name === '管理员'"
                    class="operation-button"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="handleDeleteRole(scope.row)"
                    :disabled="scope.row.name === '管理员'"
                    class="operation-button"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- Footer pagination -->
          <div class="footer-pagination" v-if="roles.length > 10">
            <el-pagination
              background
              layout="total, prev, pager, next, jumper"
              :total="roles.length"
              :page-size="10"
              :current-page="1"
              prev-text="上一页"
              next-text="下一页"
              :pager-count="5"
            />
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 角色编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="editMode ? `编辑角色 - ${currentRole?.name || ''}` : '新建角色'"
      width="66.7%"
      :destroy-on-close="true"
      top="5vh"
    >
      <el-form :model="roleForm" label-width="100px" class="role-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" required>
              <el-input 
                v-model="roleForm.name" 
                placeholder="请输入角色名称"
                :disabled="editMode && currentRole?.name === '管理员'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色描述">
              <el-input 
                v-model="roleForm.description" 
                type="textarea" 
                placeholder="请输入角色描述"
                :rows="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="center">权限设置</el-divider>
        
        <el-form-item>
          <el-alert
            v-if="roleForm.permissions.includes('*')" 
            type="success" 
            :closable="false"
            show-icon
            class="all-permissions-alert"
          >
            <template #title>
              已授予所有权限（包括现有权限和将来添加的新权限）
            </template>
          </el-alert>
          
          <div v-else class="permission-groups">
            <el-card 
              v-for="group in availablePermissions" 
              :key="group.resource" 
              class="permission-group-card"
              :class="{ 'has-permissions': permissionCounts[group.resource]?.selected > 0 }"
              shadow="hover"
            >
              <template #header>
                <div class="permission-group-header">
                  <div class="resource-info">
                    <el-icon><component :is="group.icon" /></el-icon>
                    <span class="permission-resource">{{ group.label }}</span>
                  </div>
                  
                  <div class="resource-select">
                    <el-checkbox 
                      :model-value="isResourceFullySelected(group.resource)"
                      :indeterminate="isResourcePartiallySelected(group.resource)"
                      @change="toggleResourcePermissions(group.resource, $event)"
                    >
                      全选 {{ permissionCounts[group.resource]?.selected || 0 }}/{{ group.actions.length }}
                    </el-checkbox>
                  </div>
                </div>
              </template>
              
              <div class="permission-actions-grid">
                <el-checkbox 
                  v-for="action in group.actions" 
                  :key="`${group.resource}:${action.id}`"
                  :model-value="isPermissionSelected(group.resource, action.id)"
                  @change="togglePermission(group.resource, action.id)"
                  class="permission-action-checkbox"
                >
                  {{ action.label }}
                </el-checkbox>
              </div>
            </el-card>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole" :loading="loading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  
  <el-result
    v-else
    icon="error"
    title="权限不足"
    sub-title="很抱歉，您没有权限访问角色管理页面"
  >
    <template #extra>
      <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
    </template>
  </el-result>
</template>

<style scoped>
.role-management-container {
  padding: 16px;
  background-color: #f5f7fa;
  height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.role-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0;
}

.page-title {
  display: flex;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.card-body {
  flex: 1;
  overflow: auto;
  position: relative;
  padding: 6px 0 60px 0;
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.loading-container .el-icon {
  font-size: 2rem;
  margin-bottom: 10px;
}

.loading-text {
  color: #909399;
}

.table-container {
  height: 100%;
  overflow: auto;
  padding-bottom: 10px;
}

.footer-pagination {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 15px 0;
  background-color: white;
  border-top: 1px solid #EBEEF5;
  z-index: 1;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.permission-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.permission-icon {
  margin-right: 4px;
  vertical-align: middle;
}

.permission-count {
  font-size: 12px;
  opacity: 0.8;
  margin-left: 4px;
}

.permission-groups {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-top: 0;
}

.permission-group-card {
  border-radius: 4px;
  transition: all 0.3s;
  border: 1px solid #ebeef5;
  background-color: #ffffff;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.permission-group-card.has-permissions {
  border-color: #b3d8ff;
  background-color: #ecf5ff;
}

.permission-group-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.permission-group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #ffffff;
  border-bottom: 1px solid #ebeef5;
  flex-shrink: 0;
}

.resource-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.permission-resource {
  font-weight: 500;
  color: #303133;
  font-size: 13px;
}

.permission-actions-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  padding: 12px;
  flex-grow: 1;
  text-align: center;
}

.permission-action-checkbox {
  margin-right: 0 !important;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  justify-content: center;
}

.all-permissions-alert {
  margin: 0 0 16px 0;
  padding: 8px 16px;
}

.role-name-cell {
  display: flex;
  align-items: center;
}

.el-divider {
  margin: 16px 0;
}

.el-divider__text {
  font-size: 13px;
  font-weight: 500;
  color: #606266;
  padding: 0 16px;
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 2px;
  flex-wrap: nowrap;
  white-space: nowrap;
  overflow-x: auto;
}

.action-buttons::-webkit-scrollbar {
  display: none;
}

.action-buttons {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.operation-button {
  padding: 5px 10px;
  font-size: 12px;
  height: 28px;
  line-height: 1;
  margin-left: 0;
  margin-right: 3px;
}

/* 调整卡片头部内边距 */
:deep(.el-card__header) {
  padding: 10px 20px;  /* 将默认的 20px 内边距减半为 10px */
}

/* Table styles */
:deep(.el-table) {
  margin-top: 0;
}

/* El-card styles */
:deep(.el-card) {
  margin-top: 6px;
}

/* Button styles */
:deep(.el-button) {
  border-radius: 4px;
  transition: all 0.3s;
}

/* Optimize add button style */
:deep(.el-button .el-icon) {
  margin-right: 4px;
  font-size: 14px;
}

:deep(.el-button--small) {
  padding: 5px 10px;
  font-size: 12px;
  height: 28px;
  line-height: 1;
  margin-left: 0;
  margin-right: 3px;
}

/* Tag styles */
:deep(.el-tag) {
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
  font-size: 12px;
  border-radius: 2px;
}

/* Dialog styles */
:deep(.el-dialog) {
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__header) {
  padding: 16px;
  margin: 0;
  background-color: #ffffff;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 16px;
  max-height: 75vh;
  overflow-y: auto;
}

:deep(.el-dialog__footer) {
  padding: 12px 16px;
  background-color: #ffffff;
  border-top: 1px solid #ebeef5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* Responsive adjustments */
@media screen and (max-width: 1200px) {
  .permission-groups {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media screen and (max-width: 768px) {
  .permission-groups {
    grid-template-columns: 1fr;
  }
}

/* Table styles */
:deep(.el-table__fixed-right) {
  height: auto !important;
}

:deep(.el-table__fixed-right .el-table__fixed-body-wrapper) {
  height: auto !important;
  position: absolute;
  top: 0;
  right: 0;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}
</style> 